package com.atguigu.jxc.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.jxc.dao.OverflowDao;
import com.atguigu.jxc.dao.UserDao;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.entity.*;
import com.atguigu.jxc.service.OverflowService;
import com.atguigu.jxc.util.StringUtil;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OverflowServiceipl implements OverflowService {
    @Autowired
    private OverflowDao overflowDao;
    @Autowired
    private UserDao userDao;

    @Transactional
    @Override
    public ServiceVO overflowListGoods(OverflowList overflowList, String overflowListGoodsStr) {

        //获取当前登录的用户名
        String userName = (String) SecurityUtils.getSubject().getPrincipal();
        //根据用户名查询用户信息
        User user = userDao.findUserByName(userName);
        overflowList.setUserId(user.getUserId());
        overflowList.setTrueName(user.getTrueName());
        int count=0;
        List<OverflowListGoods> overflowListGoodsList=null;
        if(!StringUtil.isEmpty(overflowListGoodsStr)){
            overflowListGoodsList = JSONObject.parseArray(overflowListGoodsStr, OverflowListGoods.class);
        }
        //把damageList对象放在t_damage_list表中
        overflowDao.saveOverflowList(overflowList);
        for (OverflowListGoods overflowListGood : overflowListGoodsList) {
            overflowListGood.setOverflowListId(overflowList.getOverflowListId());
            count=overflowDao.saveOverflowListGoods(overflowListGood);
        }
        if(count>0){
            return new ServiceVO(100,"请求成功");
        }
        return new ServiceVO(250,"请求失败");
    }

    //查询报溢单列表
    @Override
    public Map<String, Object> overflowList(String sTime, String eTime) {
        HashMap<String, Object> map = new HashMap<>();
        List<OverflowList> overflowList=overflowDao.overflowListGoods(sTime,eTime);
        User user = new User();

        for (OverflowList list : overflowList) {
            Integer userId = list.getUserId();
            user= userDao.getUserById(userId);
            String trueName = user.getTrueName();
            list.setTrueName(trueName);
        }
        map.put("rows",overflowList);
        return map;
    }

    //查询报溢单商品信息
    @Override
    public Map<String, Object> overflowListGoodsList(Integer overflowListId) {
        HashMap<String, Object> map = new HashMap<>();
        List<OverflowListGoods> list=overflowDao.overflowListGoodsList(overflowListId);
        map.put("rows",list);
        return map;
    }
}
